package controller.algo;

import java.util.ArrayList;

import model.Edge;
import model.container.edges.*;
import model.container.vertices.*;

public class Prim extends Algo {
	private AdjacencyList vertices;
	private AdjacencyList verticesT;
	private Edges edges ;
	private ArrayList<Edge> edgesN;

	private int cost = 0;

	public Prim() {
	}

	@Override
	public void loadEdges(Edges t) {
		edges = t;
	}

	@Override
	public void loadVertices(AdjacencyList v) {
		vertices = v;
	}

	@Override
	public ArrayList<Edge> getNewEdges() {
		return edgesN;
	}

	@Override
	public boolean process() {
		ArrayList<Edge> edgesT = new ArrayList<Edge>();
		verticesT = new AdjacencyList();
		edgesN = new ArrayList<Edge>();
		boolean changed = false;

		Edge e = edges.getMinimal();
		//System.out.println(getClass()+" [+] Adding (0) verified item "+e);
		verticesT.addItem(e);
		verticesT.addItem(e.revert());
		edgesN.add(e);

		cost += e.getCost();
		while(edgesN.size() < vertices.getSize()-1) {
			if(changed) {
				for(Edge c : edgesT)
					edges.addItem(c);
        edgesT.clear();
				changed = false;
			}

			e = edges.getMinimal();
			if(isVerified(e, verticesT)) {
				//System.out.println(getClass()+" [+] Adding (2) verified item "+e);
				verticesT.addItem(e);
				verticesT.addItem(e.revert());
				edgesN.add(e);
				cost += e.getCost();
				changed = true;
			} else {
				//System.out.println(getClass()+" [+] foo Saving it for later "+e);
				edgesT.add(e);
			}
		}

		return true;
	}
	
	private boolean isVerified(Edge e, AdjacencyList l) {
		return (l.getItemList(e.getFrom()) != null || l.getItemList(e.getTo()) != null); 
	}

	@Override
	public int getCost() {
		return cost;
	}

}
